﻿using MimeKit;
using MimeKit.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WeChat.PlatForm.Common
{
    public class CommonHelp
    {
        static string mailFromAccount = "15821612704@163.com";
        static string mailPassword = "123456000000c";
        static string mailFrom = string.Format("{0}<15821612704@163.com>", "明工作之道");

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mailTo">收件人</param>
        /// <param name="subject">标题</param>
        /// <param name="body">内容</param>
        /// <param name="path">附件地址，默认空</param>
        public static Task SmtpClient(string mailTo, string subject, string body, string path = "")
        {
            return Task.Run(() =>
            {
                MailMessage mymail = new MailMessage();
                mymail.From = new MailAddress(mailFrom);
                mymail.To.Add(mailTo);
                mymail.Subject = string.Format(subject);
                mymail.Body = body;
                mymail.IsBodyHtml = true;
                if (!string.IsNullOrEmpty(path))
                {
                    mymail.Attachments.Add(new Attachment(path));
                }

                SmtpClient smtpclient = new SmtpClient();
                smtpclient.Port = 25;
                smtpclient.UseDefaultCredentials = false;
                smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpclient.Host = "smtp.163.com";
                smtpclient.EnableSsl = true;
                smtpclient.Credentials = new NetworkCredential(mailFromAccount, mailPassword);
                try
                {
                    smtpclient.Send(mymail);
                }
                catch (Exception ex)
                {
                    //抛出问题，这里应该记录日志。先不写
                    throw new Exception(ex.Message);
                }
            });
        }

        ///   <summary>
        ///   给一个字符串进行MD5加密
        ///   </summary>
        ///   <param   name="strText">待加密字符串</param>
        ///   <returns>加密后的字符串</returns>
        public static string MD5Encrypt(string strText)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(strText));
            return Encoding.Default.GetString(result);
        }
    }
}
